from odoo import fields, models, api
from odoo.exceptions import UserError
from ...api.encapsulate.pickup import Pickup
import pytz
from datetime import datetime, time

time_select = {'time_one': 8, 'time_two': 10, 'time_three': 12, 'time_four': 14, 'time_five': 16}


class RPBookPickupInherit(models.Model):
    _inherit = 'rp.book.pickup'

    shippypro_code = fields.Char(string='ShipPyPro编码', copy=False, help='ConfirmationID', tracking=True)
    shippypro_flag = fields.Boolean(string='ShipPyPro对接成功', default=False, tracking=True)
    shippypro_desc = fields.Text(string='ShipPyPro描述', tracking=True)

    def confirm_book(self):
        """ 确认预约 """
        if self.state in ['initiated', 'book_failure']:
            # 获取公司商用email
            email = self.env['ir.config_parameter'].search([('key', '=', 'palment_email')])
            # 获取发件地址信息
            # sender = self.ship_from
            display_name = None
            for name in (self.send_last_name, self.send_first_name):
                if name:
                    if not display_name:
                        display_name = name
                    else:
                        display_name = display_name + ' ' + name
            
            from_address = Pickup.address(display_name,
                                          self.send_company_name,
                                          self.send_country_id.code,
                                          self.send_state_id.name,
                                          self.send_city_id.name,
                                          self.send_street,
                                          self.send_postal_code_id.name,
                                          self.send_phone,
                                          self.shipment_id.send_email)
            # 获取包裹信息
            parcel_list = []
            for p in self.rp_parcel_ids:
                parcel_list.append({"length": p.depth, "width": p.width, "height": p.height, "weight": p.weight})
            parcels = Pickup.parcels(parcel_list)
            # 获取预约时间
            book_timestamp = self.get_book_timestamp()
            if not self.shipper_mail_route_id.courier_mail_route_id.third_server_id:
                raise UserError("托运商对应的承运商邮路，第三方服务编号为空。")
            flag, result = Pickup.book_pickup(from_address, self.send_country_id.code, parcels,
                                              self.shipper_id.courier_id.name, int(self.shipper_mail_route_id.courier_mail_route_id.third_server_id),
                                              book_timestamp, self.book_note)
            if flag:
                self.write({'shippypro_flag': True,
                            'shippypro_desc': result['message'],
                            'shippypro_code': result['confirmation_id'],
                            'state': 'booked'})
            else:
                self.write({'shippypro_flag': False,
                            'shippypro_desc': result,
                            'state': 'book_failure'})

    def cancel_book(self):
        super(RPBookPickupInherit, self).cancel_book()
        if self.state == 'booked':
            flag, result = Pickup.cancel_pickup(self.courier_id.name, int(self.courier_service_id.shippypro_id),
                                                self.shippypro_code, self.get_book_timestamp())
            if flag:
                self.write({'shippypro_desc': result['message'],
                            'shippypro_code': False,
                            'state': 'cancel',
                            'active': False})
            else:
                self.write({'shippypro_desc': result})

    def get_book_timestamp(self):
        """ 通过时间、时刻计算时间戳 """
        # dt = datetime.combine(self.book_d, time(time_select[self.book_t], tzinfo=pytz.timezone(self.env.user.tz)))
        if not self.book_d or not self.book_t:
            raise UserError("上门取件的预约时间未设置。")
        dt = datetime.combine(self.book_d, time(self.book_t.start_hour, tzinfo=pytz.timezone(self.env.user.tz)))
        book_timestamp = dt.timestamp()
        return book_timestamp
